package com.buba.springcloud.controller;
import com.buba.springcloud.entities.CommonResult;
import com.buba.springcloud.entities.HfUser;
import com.buba.springcloud.service.UserService;
import com.buba.springcloud.util.AliyunOSSUtil;
import com.buba.springcloud.util.JwtUtil;
import com.buba.springcloud.util.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

/**
 * autor：肖宝兴
 **/
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Resource
    private AliyunOSSUtil aliyunOSSUtil;

    @Resource
    private UserService userService;

    @Resource
    private RedisUtil redisUtil;

    //查询登录id的个人信息
    @GetMapping("/findById")
    public CommonResult findUserById(HttpServletRequest request) {
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT(token);
        String id = claims.get("id").toString();
        HfUser hfUser =(HfUser) redisUtil.get("id");
        return new CommonResult(200, "查询成功" , hfUser);
    }

    /**
     * 修改
     * @param hfUser
     * @return
     */
    @PostMapping("/updateUser")
    public CommonResult updateUser(@RequestBody HfUser hfUser){
        Integer integer = userService.updateUser(hfUser);
        if (integer > 0 ){
            return new CommonResult(200,"修改成功",hfUser);
        }
        return new CommonResult(500,"修改失败");
    }

    /**
     * 图片上传并返回url
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public CommonResult upload(@RequestParam("userAvatar") MultipartFile file) {
        URL resource = UserController.class.getClassLoader().getResource("");
        String dir = resource.getPath() + "public";
        System.out.println(dir);
        String userAvatar = null;
        File baseDir = new File(dir);
        if (!baseDir.exists()) {
            baseDir.mkdir();
        }
        String fileName = file.getOriginalFilename();
        File newFile = new File(dir + "/" + fileName);
        try {
            file.transferTo(newFile);
            userAvatar = aliyunOSSUtil.upLoad(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonResult(200,"上传成功",userAvatar);
    }




}
